<-- back

Swap Nodes in Pairs

Link

Simply switch the place of two nodes. The real "gotcha" of this problem is to make sure you store the last node of the previously switched nodes so that you can connect each switch.

Full Solution in Java:

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode swapPairs(ListNode head) { if(head==null){ return null; } if(head.next==null){ return head; } ListNode result = head.next; ListNode temp = new ListNode(0); while(true){ ListNode two = head.next; head.next = two.next; two.next = head; temp.next = two; temp = head; head = head.next; if(head==null || head.next==null){ break; } } return result; } }